import { AsyncSubject, Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import { Page } from '../models/page-models/page';
import { TmpComItem } from '../models/page-models/tmp-com-item';
import { BaseService } from './base.service';

@Injectable({
  providedIn: 'root'
})
export class PageService extends BaseService {
  currentPage: Page;

  pageBtnShowOrHide$ = new Subject<boolean>();
  auditBtnClick$ = new Subject();


  getTmpComItems() {
    let r: TmpComItem[] = [];
    if (this.currentPage) {
      this.currentPage.pageTmpItems.forEach(item => {
        r = r.concat(item.template.tmpComItems);
      })
    }
    return r;
  }

  getPageById(pageId: string) {
    const url = `api/page/${pageId}`;
    return this.get(url);
  }

  makeFile(model, fileUrl, fileType, ft) {
    model = this.formateData(model);
    let data = {
      DynamicData: JSON.stringify(model),
      TemplateUrl: fileUrl,
      FileType: fileType
    }

    let url = 'http://filegen.zepride.com/Export/WordDynamicGenerate';
    if (ft == 'word') {
      url = 'http://filegen.zepride.com/Export/WordDynamicGenerate';
    }
    else if (ft == 'excel') {
      url = 'http://filegennet5.zepride.com/Export/ExcelDynamicGenerate';
    }

    return this.post(url, data, { absolutelyUrl: true });
  }

  makeMergePDF(fileUrls: string[]) {
    let url = 'http://filegennet5.zepride.com/Export/MergePDFFiles';

    return this.post(url, fileUrls, { absolutelyUrl: true });
  }

  formateData(data) {
    data = JSON.parse(JSON.stringify(data));

    for (let key in data) {
      if (data[key] && data[key].ts) {
        data[key] = data[key].display;
      }
    }


    return data;
  }

}
